package com.moji.util;

import org.apache.commons.lang3.time.DateFormatUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.time.LocalDate;
import java.util.Date;
import java.util.concurrent.TimeUnit;

/**
 * @author ccl
 * @date 2023年3月17日
 */
@Component
public class IdGenerator {

    @Autowired
    private RedisTemplate redisTemplate;


    /**
     * 标签字母+年月日+4位数递增。举例：GYWM-240417-0001
     * @param
     * @return code
     */
    public String idGenerator(String label) {
        String taDay= DateFormatUtils.format(new Date(), DateUtils.UNSIGNED_DATE_PATTERN);
        String key = label + taDay;
        Long increment = this.redisTemplate.opsForValue().increment(key, 1L);
        if (increment == 1L) {
            this.redisTemplate.expire(key, 24L, TimeUnit.HOURS);
        }
        String code = String.format(label + "-" + taDay.substring(2) + "-%04d", increment);
        return code;
    }
}